package com.zyp.test.test;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * @author zyp
 *         2017/11/21
 */

public class SlidingItemView extends LinearLayout {

    private View mRightView;
    private Scroller mScroller;

    public SlidingItemView(Context context) {
        super(context);
        initView(context);
    }

    public SlidingItemView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        setOrientation(HORIZONTAL);
        mScroller = new Scroller(context,null,true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mRightView = getChildAt(1);
        
    }
    private float startX;
    private float startY;
    private float dx;
    private float dy;
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = ev.getX();
                startY = ev.getY();
                super.dispatchTouchEvent(ev);
                return true;
            case MotionEvent.ACTION_MOVE:
                dx = ev.getX() - startX;
                dy = ev.getY() - startY;
                if(Math.abs(dx) - Math.abs(dy) > ViewConfiguration.getTouchSlop()){
                    if(getScrollX() + (-dx) > mRightView.getWidth() || getScrollX() - dx < 0){
                        return true;
                    }
                   scrollBy((int) -dx,0);
                    startX = ev.getX();
                    startY = ev.getY();
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                float i = getScrollX() / (float)mRightView.getWidth();
                Log.d("aaa",i+"");
                int offset = i > 0.5f ? mRightView.getWidth() - getScrollX() : -getScrollX();
                mScroller.startScroll(getScrollX(),getScrollY(),offset,0);
                invalidate();
                startX = 0;
                startY = 0;
                dx = 0;
                dy = 0;
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
       if(mScroller.computeScrollOffset()){
           scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
           postInvalidate();
       }
    }
}
